package com.study.crypto.utils;

import org.apache.commons.codec.binary.Base64;
import org.bouncycastle.asn1.x500.X500Name;
import org.bouncycastle.asn1.x509.SubjectPublicKeyInfo;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.operator.ContentSigner;
import org.bouncycastle.operator.jcajce.JcaContentSignerBuilder;
import org.bouncycastle.pkcs.PKCS10CertificationRequest;
import org.bouncycastle.pkcs.PKCS10CertificationRequestBuilder;

import java.security.PrivateKey;
import java.security.PublicKey;

/**
 * @author Songjin
 * @since 2023-03-21 18:30
 */
public final class Pkcs10Utils {

    private Pkcs10Utils() {
    }

    /**
     * 生成证书请求字符串
     * @param privateKey 私钥
     * @param publicKey 公钥
     * @param dn DN字符串
     * @param signAlg 签名算法
     * @return 证书请求字符串
     */
    public static String createCertificateRequest(PrivateKey privateKey, PublicKey publicKey, String dn, String signAlg) throws Exception {
        X500Name subject = new X500Name(dn);
        SubjectPublicKeyInfo publicKeyInfo = SubjectPublicKeyInfo.getInstance(publicKey.getEncoded());
        PKCS10CertificationRequestBuilder builder = new PKCS10CertificationRequestBuilder(subject, publicKeyInfo);
        JcaContentSignerBuilder jcaContentSignerBuilder = new JcaContentSignerBuilder(signAlg);
        jcaContentSignerBuilder.setProvider(BouncyCastleProvider.PROVIDER_NAME);
        ContentSigner contentSigner = jcaContentSignerBuilder.build(privateKey);
        PKCS10CertificationRequest csr = builder.build(contentSigner);
        return Base64.encodeBase64String(csr.getEncoded());
    }
}
